<?php
namespace app\ectool;

use think\facade\Request;
use think\facade\Cache;
use think\facade\Session;
// 阿里云sms方法
// 官方文档 https://help.aliyun.com/product/44282.html
class Aliyunsms {
    
    /**
     * mains() 调用此接口发送短信
     *
     * $mobile 手机号
     * $code 验证码
    **/
    public static function mains($mobile){

        //具体配置请参考  https://help.aliyun.com/product/44282.html
        $data = [
            'accessKeyId' => '',                 //accessKeyId
            'accessKeySecret' => '',         //accessKeySecret
            'signName'    => '',                    //签名
            'templateCode' => '',         //模板编号
            'templatePara' => 'code'       //模板中的变量
        ];
        
        $code = smscode();
        
        if(!$mobile){
           json_exit(1,'手机号为空');  
        }
        
        //ip防止刷短信
        $ip = $_SERVER['REMOTE_ADDR'];
        if(!Cache::get($ip)){
            //@key ip @value time
            Cache::set($ip, time(), 60);
        }else{
            json_exit(1,'请求频繁'); 
        }
        
        //保存短信
        Session::set('alisms_code', $code);

        $sms = new \app\common\AliyunSms($data);

        $status = $sms->send_verify($mobile,$code);

        if(!$status){
            //短信发送失败
            json_exit(1,'发送失败');
        }
        json_exit(0,'发送成功');
        
        function json_exit($code,$msg){
            exit(json_encode(['code'=>$code,'msg'=>$msg]));
        }

        function smscode($length = 6){
            //字符组合
            $str = '0123456789';
            $len = strlen($str)-1;
            $randstr = '';
            for ($i=0;$i<$length;$i++) {
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
            }
            return $randstr;
        }
        
    }
    
}

